//
//  MessageField.swift
//  Automobile
//
//  Created by erkebulan elzhan on 8/24/20.
//  Copyright © 2020 erkebulan elzhan. All rights reserved.
//

import UIKit
import SnapKit


final class MessageField: UIView {
    private lazy var messageField: UITextView = {
        let view = UITextView()
        view.sizeToFit()
        view.font = .systemFont(ofSize: 17)
        view.text = placeholder
        view.backgroundColor = .white
        view.textColor = .rgb(60,72,88)
        view.isScrollEnabled = false
        view.layer.cornerRadius = 5
        view.textContainerInset = UIEdgeInsets(top: 8, left: 8, bottom: 4, right: 8)
        view.delegate = self
        return view
    }()
    
    lazy var sendButton: UIButton = {
        let btn = UIButton()
        btn.setImage(UIImage(named: "message"), for: .normal)
        btn.backgroundColor = .blueColor
        btn.layer.cornerRadius = 20
        return btn
    }()
    
    let placeholder = "Напишите что-нибудь"
    
    init () {
        super.init(frame: .zero)
        self.backgroundColor = .lightBlueColor
        self.addViews()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    public func getText () -> String {
        return messageField.text.trimmingCharacters(in: .whitespacesAndNewlines)
    }
    
    public func restartUI() {
        messageField.text = placeholder
        self.hideKeyboard()
    }
    
    public func hideKeyboard () {
        messageField.resignFirstResponder()
    }
    
    
    
    private func addViews () {
        addSubview(sendButton)
        addSubview(messageField)

        sendButton.snp.makeConstraints { (make) in
            make.width.height.equalTo(40)
            make.trailing.equalToSuperview().inset(16)
            make.bottom.equalToSuperview().inset(12)
        }
        messageField.snp.makeConstraints { (make) in
            make.height.greaterThanOrEqualTo(40)
            make.height.lessThanOrEqualTo(200)
            make.leading.equalToSuperview().inset(16)
            make.trailing.equalTo(sendButton.snp.leading).offset(-16)
            make.top.bottom.equalToSuperview().inset(12)
        }
    }
}



extension MessageField: UITextViewDelegate {
    func textViewDidBeginEditing(_ textView: UITextView) {
        if textView.text == placeholder {
            textView.text = ""
        }
    }
    
    func textViewDidEndEditing(_ textView: UITextView) {
        if textView.text == "" {
            textView.text = placeholder
        }
    }
}

